//
//  AppDelegate.m
//  huiliantong
//
//  Created by hlt on 15/8/4.
//  Copyright (c) 2015年 hlt. All rights reserved.
//

#import "AppDelegate.h"
#import "ZWIntroductionViewController.h"
#import "ViewController.h"
#import "HLTHomeViewController.h"
#import "HLTuserViewController.h"
#import "SearchViewController.h"
#import "cloudsearchmapViewController.h"
//#import "HLTMerchantViewController.h"
//#import "HLTmerchanthomeTableViewController.h"
#import "HLTzhoubiantuijianyouhuimerchantTableViewController.h"


#import "HLTLoginTableViewController.h"

#import "SliderViewController.h"
#import "HLTmerchanthomeViewController.h"
#import <CoreLocation/CoreLocation.h>

//分享用到的文件
#import "CommonMarco.h"
#import "WXApi.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "WeiboSDK.h"
//友盟分享的头文件
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"


#import "cloudsearchmapViewController.h"


//使用百度云推送用到的文件
#import "BPush.h"

@interface AppDelegate ()<CLLocationManagerDelegate,sliderScrollerDelegate,UITabBarControllerDelegate>
{
    //定位
    CLLocationManager *_locationManager;//用于获取位置
    CLLocation *_checkLocation;//用于保存位置信息
   
}
@property (nonatomic, strong) ZWIntroductionViewController *introductionView;

@property SliderViewController *slider;


@end
BMKMapManager* _mapManager;

@implementation AppDelegate


//设置定位
-(void)setupLocationManager{
    
    
    
    //使用百度地图准备
//    _mapManager = [[BMKMapManager alloc]init];
//    BOOL ret = [_mapManager start:@"please enter your key" generalDelegate:self];
//    
//    if (!ret) {
//        NSLog(@"manager start failed!");
//    }
    
    
    
    
    
//    
//    _latitude = LATITUDE_DEFAULT;
//    _longitude = LONGITUDE_DEFAULT;
//    _locationManager = [[CLLocationManager alloc] init];
//    
//    if ([CLLocationManager locationServicesEnabled]) {
//        NSLog(@"开始定位");
//        _locationManager.delegate = self;
//        // distanceFilter是距离过滤器，为了减少对定位装置的轮询次数，位置的改变不会每次都去通知委托，而是在移动了足够的距离时才通知委托程序
//        // 它的单位是米，这里设置为至少移动1000再通知委托处理更新;
//        _locationManager.distanceFilter = 200.0;
//        // kCLLocationAccuracyBest:设备使用电池供电时候最高的精度
//        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//        
//        
//        //ios8+以上要授权，并且在plist文件中添加NSLocationWhenInUseUsageDescription，NSLocationAlwaysUsageDescription，值可以为空
//        if (IOS_VERSION >=8.0) {//ios8+，不加这个则不会弹框
//            [_locationManager requestWhenInUseAuthorization];//使用中授权
//            [_locationManager requestAlwaysAuthorization];
//        }
//        [_locationManager startUpdatingLocation];
//    }else{
//        NSLog(@"定位失败，请确定是否开启定位功能");
//        //        _locationManager.delegate = self;
//        //        // distanceFilter是距离过滤器，为了减少对定位装置的轮询次数，位置的改变不会每次都去通知委托，而是在移动了足够的距离时才通知委托程序
//        //        // 它的单位是米，这里设置为至少移动1000再通知委托处理更新;
//        //        _locationManager.distanceFilter = 200.0;
//        //        // kCLLocationAccuracyBest:设备使用电池供电时候最高的精度
//        //        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//        //        [_locationManager startUpdatingLocation];
//    }
}





-(void)initRootVC{
    //此处一定要给window一个frame，添加广告image时这个必须要
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    
//    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    //1.
    HLTHomeViewController *VC1 = [[HLTHomeViewController alloc] init];
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:VC1];
    
    //    InfoViewController *VC2 = [[InfoViewController alloc] init];
//    HLTMerchantViewController *VC2 = [[HLTMerchantViewController alloc] init];
    
    NSMutableArray * array=[NSMutableArray array];
    
    NSArray * titiles=@[@"全部",@"优惠",@"推荐",@"周边"];
    for (int i=0; i<titiles.count; i++) {
        
        if (i==0) {
            HLTmerchanthomeViewController *nex1= [[HLTmerchanthomeViewController alloc] init];
//            nex1.type=suoyoutype;
            [array addObject:nex1];
        }
        else if (i==1)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *nex1= [[HLTzhoubiantuijianyouhuimerchantTableViewController alloc] init];
//            nex1.type=tuikuantype;
            
            
            [array addObject:nex1];
            
        }else if (i==2)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *nex1= [[HLTzhoubiantuijianyouhuimerchantTableViewController alloc] init];
//            nex1.type=yiwanchengtype;
            [array addObject:nex1];
        }else if (i==3)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *nex1= [[HLTzhoubiantuijianyouhuimerchantTableViewController alloc] init];
//            nex1.type=daiqueren;
            [array addObject:nex1];
        }
    }
    
    
    SliderViewController * next=[[SliderViewController alloc] initWithViewControllers:array];
    //            next.tag=1005;
    
    
    for (int i=0; i<[array count]; i++) {
        
        if (i==0) {
            HLTmerchanthomeViewController *vcc=array[i];
            vcc.parent=next;
        }
        else if(i==1)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *vcc=array[i];
            vcc.shoptye=youhuitype;
            vcc.parent=next;
        }
        else if (i==2)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *vcc=array[i];
            vcc.shoptye=tuijiantype;
            vcc.parent=next;
            
        }else if (i==3)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *vcc=array[i];
            vcc.shoptye=zoubian;
            vcc.parent=next;
        }
        
        
        
        
    }
    
    
    next.titileArray=titiles;
    next.lineHeight=2;
    next.selectTextColor=RGB(0, 128, 208);
    
    next.selectBgColor=[UIColor whiteColor];
    next.defaultUnSelectBgColor=[UIColor lightGrayColor];
    // next.separateColor=[UIColor redColor];
    next.selectIndex=0;
    next.sliderDelegate=self;
//    [self.navigationController pushViewController:next animated:YES];
    self.slider=next;
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:next];
    SearchViewController *VC3 = [[SearchViewController alloc] init];
    UINavigationController *nav3 = [[UINavigationController alloc] initWithRootViewController:VC3];
    HLTuserViewController *VC4 = [[HLTuserViewController alloc] init];
    UINavigationController *nav4 = [[UINavigationController alloc] initWithRootViewController:VC4];
//    HLTHomeViewController *VC5 = [[HLTHomeViewController alloc] init];
//    UINavigationController *nav5 = [[UINavigationController alloc] initWithRootViewController:VC5];
    VC1.title = @"首页";
    next.title = @"商户中心";
    VC3.title = @"搜索";
    VC4.title = @"个人中心";
//    VC5.title = @"更多发现";
    //2.
    NSArray *viewCtrs = @[nav1,nav2,nav3,nav4];
    //3.
    //    UITabBarController *tabbarCtr = [[UITabBarController alloc] init];rootTabbarCtr
    self.rootTabbarCtr  = [[UITabBarController alloc] init];
    //4.
    [self.rootTabbarCtr setViewControllers:viewCtrs animated:YES];
    //5.
    self.window.rootViewController = self.rootTabbarCtr;
    
    //6.
    UITabBar *tabbar = self.rootTabbarCtr.tabBar;
    self.rootTabbarCtr.delegate=self;
    UITabBarItem *item1 = [tabbar.items objectAtIndex:0];
    UITabBarItem *item2 = [tabbar.items objectAtIndex:1];
    UITabBarItem *item3 = [tabbar.items objectAtIndex:2];
    UITabBarItem *item4 = [tabbar.items objectAtIndex:3];
//    UITabBarItem *item5 = [tabbar.items objectAtIndex:4];
    
    
//       tintColor=[UIColor greenColor];
    
    item1.selectedImage = [[UIImage imageNamed:@"首页s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item1.image = [[UIImage imageNamed:@"首页"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item2.selectedImage = [[UIImage imageNamed:@"商户s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item2.image = [[UIImage imageNamed:@"商户"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //    item2.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
    item3.selectedImage = [[UIImage imageNamed:@"搜索s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item3.image = [[UIImage imageNamed:@"搜索hui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //    item3.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
    item4.selectedImage = [[UIImage imageNamed:@"用户中心s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item4.image = [[UIImage imageNamed:@"用户中心"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //    item4.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
//    item5.selectedImage = [[UIImage imageNamed:@"更多发现s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    item5.image = [[UIImage imageNamed:@"更多发现"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //    item5.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
    
    //改变UITabBarItem字体颜色
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:RGB(113, 158,255),UITextAttributeTextColor, nil] forState:UIControlStateSelected];
    
    
    
    
    //友盟初始化
//    [UMSocialData setAppKey:UMAPPKEY];
//    [UMSocialWechatHandler setWXAppId:@"wx3b1ec5fee404cc3d" appSecret:@"e97199313f931035a765ee433e335dbb" url:@"http://www.fityun.cn/"];
//    
//    //友盟初始化，对未安装QQ，微信的平台进行隐藏
//    //    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline]];
//    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToWechatSession,UMShareToWechatTimeline]];
//    
    
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self.window makeKeyAndVisible];
    
    
    [self initNavigationBar:next];
}





#pragma mark tabbar的委托，实现动态进入登陆界面的
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    NSLog(@"--tabbaritem.title--%@",viewController.tabBarItem.title);
    
    Account *acc=[[AccountTool sharedAccountTool ]currentAccount];
    //这里我判断的是当前点击的tabBarItem的标题
    if ([viewController.tabBarItem.title isEqualToString:@"个人中心"]) {
        //如果用户ID存在的话，说明已登陆
        
        if (![acc.pwd isEqualToString:@""]) {
            return YES;
        }
        else
        {
            //跳到登录页面
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            HLTLoginTableViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:@"HLTLoginTableViewController"];
            //隐藏tabbar,由于这里跳转的原理是利用之前的页面跳转，所以必须隐藏tabbar，否则会出现点击多次个人中心之后点其他的还是登陆页面的情况
            vc.yinchang=YES;
            vc.hidesBottomBarWhenPushed = YES;
            [((UINavigationController *)tabBarController.selectedViewController) pushViewController:vc animated:NO];
            
            return NO;
        }
    }
    else
        return YES;
}



//然后呢当然是自定义我们的navigation bar了
-(void)initNavigationBar:(SliderViewController *) slider
{
    //添加地图按钮
//    UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 45, 30)];
//    //[moreButton setTitle:@"地图" forState:UIControlStateNormal];
//    [moreButton setImage:[UIImage imageNamed:@"icon_homepage_map_old"] forState:UIControlStateNormal];
//    [moreButton addTarget:self action:@selector(handleMore:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *moreItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];
//    
    
    
    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [searchButton setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(startSearch:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:searchButton];
    //     self.navigationItem.rightBarButtonItems = @[searchItem,moreItem];
    slider.navigationItem.rightBarButtonItems = @[searchItem];
    
    
    
    
    slider.navigationController.navigationBar.barTintColor = navigationBarColor;
}

//实现搜索按钮点击事件
#pragma mark - handle button click
-(void) startSearch:(id)sender
{
    
    
    SearchViewController *search1= [[SearchViewController alloc] init];
    search1.sourceType = SearchBarTypeHome;
    [self.slider.navigationController pushViewController:search1 animated:NO];
    
    
    
}

//跳转到map界面
- (void) handleMore:(id )sender
{
    
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    cloudsearchmapViewController * map = [story instantiateViewControllerWithIdentifier:@"zoubianmap"];
   
    [self.slider.navigationController pushViewController:map animated:NO];
    
}




#pragma mark slider的委托
-(void)sliderScrollerDidIndex:(NSInteger)index andSlider:(SliderViewController *)slider{
    
    NSString * tiitle=slider.titileArray[index];
     [slider.navigationItem setTitle:tiitle];
    
    //设置导航的标题的字体大小和颜色
    [slider.navigationController.navigationBar setTitleTextAttributes:
     
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
//    slider.navigationController.title=tiitle;
}

#pragma mark - 处理分享之后的返回事件
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    if ([[url absoluteString] hasPrefix:@"tencent"]) {
//        
//        return [TencentOAuth HandleOpenURL:url];
//        
//    }else if([[url absoluteString] hasPrefix:@"wb"]){
//        
//        return [WeiboSDK handleOpenURL:url delegate:self];
//        
//    }
//    
//    return NO;
//}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}







#pragma mark - 处理分享之后的返回事件

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
//{
//    return [TencentOAuth HandleOpenURL:url];
//}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}

/**
 *  初始化第三方组件
 */
- (void)init3rdParty
{
    [WXApi registerApp:APP_KEY_WEIXIN];
    
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:APP_KEY_WEIBO];
    
}





- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
    
    
    
    
    
    
    //使用百度云推送需要的配置
    
    // iOS8 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    //    #warning 测试 开发环境 时需要修改BPushMode为BPushModeDevelopment 需要修改Apikey为自己的Apikey
    
    // 在 App 启动时注册百度云推送服务，需要提供 Apikey
    [BPush registerChannel:launchOptions apiKey:@"cG88ZHZbzVM08ptUPywtq9PI" pushMode:BPushModeDevelopment withFirstAction:nil withSecondAction:nil withCategory:nil isDebug:YES];
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        NSLog(@"从消息启动:%@",userInfo);
        [BPush handleNotification:userInfo];
    }
#if TARGET_IPHONE_SIMULATOR
    Byte dt[32] = {0xc6, 0x1e, 0x5a, 0x13, 0x2d, 0x04, 0x83, 0x82, 0x12, 0x4c, 0x26, 0xcd, 0x0c, 0x16, 0xf6, 0x7c, 0x74, 0x78, 0xb3, 0x5f, 0x6b, 0x37, 0x0a, 0x42, 0x4f, 0xe7, 0x97, 0xdc, 0x9f, 0x3a, 0x54, 0x10};
    [self application:application didRegisterForRemoteNotificationsWithDeviceToken:[NSData dataWithBytes:dt length:32]];
#endif
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        // 绑定返回值
    }];
    
    
    // 测试本地通知
    //    [self performSelector:@selector(testLocalNotifi) withObject:nil afterDelay:1.0];
    
    
    
    
    
    //使用百度地图准备
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"cG88ZHZbzVM08ptUPywtq9PI" generalDelegate:self];
    
    if (!ret) {
        NSLog(@"manager start failed!");
    }

    
    //使用友盟分享wxd930ea5d5a258f4f
    [UMSocialData setAppKey:@"561b771c67e58eb172000bd4"];
    [UMSocialWechatHandler setWXAppId:@"wx37a144e4dd4c0973" appSecret:@"d4624c36b6795d1d99dcf0547af5443d" url:@"https://itunes.apple.com/cn/app/id1057062644"];
    [UMSocialQQHandler setQQWithAppId:@"1104899095" appKey:@"xhiA9ghOhUc08AiW" url:@"https://itunes.apple.com/cn/app/id1057062644"];

   

    
    
    
    
    // Override point for customization after application launch.
    //添加一个签到密钥，每天都会改变的
    Account *acc=[[AccountTool sharedAccountTool] currentAccount];
    if ([acc.pwd isEqual:@""]) {
        acc=[[Account alloc]init];
        acc.cardType=@"";
        acc.custIdent=@"";
        acc.cardNo=@"";
        acc.custName=@"";
        acc.custIType=@"";
        acc.custPhone=@"";
        acc.custAddr=@"";
        acc.custSex=@"";
        acc.custFlag=@"";
        acc.modiDate=@"";
        acc.pwd=@"";
        acc.YKTCardBalance=@"";
        acc.YKTCardJF=@"";
        acc.HaveYKTCard=@"";
        acc.NickName=@"";
        acc.HeadImg=@"";
        acc.WeXinId=@"";
        acc.Email=@"";
        acc.CheckTime=@"";
        
        acc.WorkGuid=@"{015A26A7-19B5-4F5E-A910-23F6A93A04B3}";
        acc.xhtpwd=@"6NP8DLD26F26H82R6V4J4B2X";
        acc.uid=@"96696021";
        [[AccountTool sharedAccountTool] addAccounts:acc];
        
        
    }
    else
    {
        
        if (!acc) {
            acc=[[Account alloc]init];
            acc.cardType=@"";
            acc.custIdent=@"";
            acc.cardNo=@"";
            acc.custName=@"";
            acc.custIType=@"";
            acc.custPhone=@"";
            acc.custAddr=@"";
            acc.custSex=@"";
            acc.custFlag=@"";
            acc.modiDate=@"";
            acc.pwd=@"";
            acc.YKTCardBalance=@"";
            acc.YKTCardJF=@"";
            acc.HaveYKTCard=@"";
            acc.NickName=@"";
            acc.HeadImg=@"";
            acc.WeXinId=@"";
            acc.Email=@"";
            acc.CheckTime=@"";
            
            acc.WorkGuid=@"{015A26A7-19B5-4F5E-A910-23F6A93A04B3}";
            acc.xhtpwd=@"6NP8DLD26F26H82R6V4J4B2X";
            acc.uid=@"96696021";
            [[AccountTool sharedAccountTool] addAccounts:acc];
            
        }
    }
    
    
    
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
        self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]] ;
        
        //设置之后下一次打开就不会再驱动引导页面了
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        NSLog(@"第一次启动");
        
        // Added Introduction View Controller
        NSArray *coverImageNames = @[@"q", @"q", @"q"];
        NSArray *backgroundImageNames = @[@"img_index_01bg", @"img_index_02bg", @"img_index_03bg"];
//        self.introductionView = [[ZWIntroductionViewController alloc] initWithCoverImageNames:coverImageNames backgroundImageNames:backgroundImageNames];
        
        //自定义最后一页的按钮
        UIButton *enterButton = [UIButton new];
        [enterButton setBackgroundImage:[UIImage imageNamed:@"bg_mycenter_topbar"] forState:UIControlStateNormal];
        self.introductionView = [[ZWIntroductionViewController alloc] initWithCoverImageNames:coverImageNames backgroundImageNames:backgroundImageNames button:enterButton];
        
//        [self.window addSubview:self.introductionView.view];
        self.window.rootViewController = self.introductionView;
        __weak AppDelegate *weakSelf = self;
        //以下是导航结束进入的界面
        self.introductionView.didSelectedEnter = ^() {
            [weakSelf.introductionView.view removeFromSuperview];
            weakSelf.introductionView = nil;
            [weakSelf initRootVC];
            [weakSelf setupLocationManager];
//            UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//            ViewController * mainVC = [story instantiateViewControllerWithIdentifier:@"viewcontroller"];
//            weakSelf.window.rootViewController = mainVC;
            
        };
        
        
    }
    else
    {
        
        NSLog(@"不是第一次启动");
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ViewController * mainVC = [story instantiateViewControllerWithIdentifier:@"viewcontroller"];
        self.window.rootViewController = mainVC;
//        [self setupLocationManager];
         [self initRootVC];
        
        
        //直接跳转到首页中去
//        tabbarViewController *tab=[tabbarViewController new];
//        self.window.rootViewController=tab;
    }
    
    
    
    return YES;
}




- (void)applicationDidFinishLaunching:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    NSLog(@"Initiating remoteNoticationssAreActive");
    if(!application.enabledRemoteNotificationTypes){
        NSLog(@"Initiating remoteNoticationssAreActive1");
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)];
    }
    UIApplication* myapp = [UIApplication sharedApplication];
    myapp.idleTimerDisabled = YES;
    
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ViewController * mainVC = [story instantiateViewControllerWithIdentifier:@"viewcontroller"];
    self.window.rootViewController = mainVC;
    //        [self setupLocationManager];
    [self initRootVC];
//    [self.window addSubview:viewController.view];
//    [self.window makeKeyAndVisible];
}







// 此方法是 用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
    // 打印到日志 textView 中
    NSLog(@"********** iOS7.0之后 background **********");
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        NSLog(@"acitve or background");
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:userInfo[@"aps"][@"alert"] message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    else//杀死状态下，直接跳转到跳转页面。
    {
//        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//        ViewController * mainVC = [story instantiateViewControllerWithIdentifier:@"viewcontroller"];
//        self.window.rootViewController = mainVC;
//        //        [self setupLocationManager];
//        [self initRootVC];
        /*
         // 根视图是普通的viewctr 用present跳转
         [_tabBarCtr.selectedViewController presentViewController:skipCtr animated:YES completion:nil]; */
    }
    
}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
    [application registerForRemoteNotifications];
    
    
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        
        // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
        if (result) {
            [BPush setTag:@"Mytag" withCompleteHandler:^(id result, NSError *error) {
                if (result) {
                    NSLog(@"设置tag成功");
                }
            }];
        }
    }];
    
    
    
    
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // App 收到推送的通知
    [BPush handleNotification:userInfo];
    NSLog(@"********** ios7.0之前 **********");
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        NSLog(@"acitve or background");
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:userInfo[@"aps"][@"alert"] message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    else//杀死状态下，直接跳转到跳转页面。
    {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ViewController * mainVC = [story instantiateViewControllerWithIdentifier:@"viewcontroller"];
        self.window.rootViewController = mainVC;
        //        [self setupLocationManager];
        [self initRootVC];
        
        
    }
    
    
    NSLog(@"%@",userInfo);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"接收本地通知啦！！！");
    [BPush showLocalNotificationAtFront:notification identifierKey:nil];
}








- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

[BMKMapView willBackGround];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  [BMKMapView didForeGround];

}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}




- (UIInterfaceOrientationMask )application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}
















#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "hlt.huiliantong" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"huiliantong" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"huiliantong.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}



#pragma mark - 定位的委托
//舍弃了
//-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
//    NSLog(@"didUpdateToLocation----");
//    _checkLocation = newLocation;
//}
//
////ios 6.0sdk以上
//-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
//    NSLog(@"didUpdateToLocation+++");
//    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
//    CLLocation *cl = [locations lastObject];
//    _latitude = cl.coordinate.latitude;
//    _longitude = cl.coordinate.longitude;
//    NSLog(@"纬度--%f",_latitude);
//    NSLog(@"经度--%f",_longitude);
//}
//
//-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
//    NSLog(@"定位失败");
//}









#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
